# 导入模块
from wxpy import *
import re
import code
from robot_function import *
import pymysql

SourceSavePath = './Resources/'

# 初始化机器人，扫码登陆
# bot = Bot(cache_path=False, console_qr=False)
bot = Bot(cache_path=True, console_qr=False)

# 启用 puid 属性，并指定 puid 所需的映射数据保存/载入路径
bot.enable_puid('wxpy_puid.pkl')

# 搜索名称含有 "公孙墨岚" 的男性深圳好友
#my_friend = bot.friends().search('公孙墨岚')

# 发送文本给好友
#my_friend.send('机器人已上线！')


# 给文件助手发送消息
bot.file_helper.send('hi! 助手')

# 打印来自其他好友、群聊和公众号的消息
@bot.register()
def print_others(msg):
    print(msg)

# 回复 my_friend 的消息 (优先匹配后注册的函数!)
@bot.register([Friend, Group])
def reply_my_friend(msg):

    #return 'received: {} ({})'.format(msg.text, msg.type)
    # print(str(msg.receive_time)[0:19])
    # print(msg.type)
    # print(str(msg.sender))
    # print(str(msg.member))
    # print((re.findall("(?<=\: ).*?(?=\>)",str(msg.sender)))[0])
    if (re.findall("(?<=\<).*?(?=\: )", str(msg.sender)))[0] == 'Group':
        # print(re.findall("(?<=\: ).*?(?=\>)",str(msg.member))[0])
        ActualNickName = re.findall("(?<=\: ).*?(?=\>)", str(msg.member))[0]
    else:
        ActualNickName = (re.findall("(?<=\: ).*?(?=\>)", str(msg.sender)))[0]
    # print(msg.text)

    msgTime = str(msg.receive_time)[0:19]
    MsgType = msg.type
    # ActualNickName  = (re.findall("(?<=\: ).*?(?=\>)",str(msg.sender)))[0]
    GroupName = (re.findall("(?<=\: ).*?(?=\>)", str(msg.sender)))[0]
    Msg_content = msg.text

    print(msgTime)
    print(MsgType)
    print(GroupName)
    print(ActualNickName)
    print(Msg_content)

    if msg.type == PICTURE:  # 如果接受到图片，就自动回复同样的图片
        # print('this is PICTURE:{}'.format(msg.file_name))
        curr_dir = os.getcwd()
        # print(curr_dir)

        # avater_dir = os.path.join(os.getcwd(),'wechat\\1\\')
        if not os.path.exists(curr_dir + "/Resources/picture/"):
            os.mkdir(curr_dir + "/Resources/picture/")
        savaPath = SourceSavePath + 'picture/' + msg.file_name
        print(savaPath)
        Msg_content = savaPath
        msg.get_file(savaPath)
        # msg.reply_image(savaPath)

    if msg.type == VIDEO:  # 如果接受到图片，就自动回复同样的图片
        # print('this is VIDEO:{}'.format(msg.file_name))
        curr_dir = os.getcwd()
        # print(curr_dir)

        # avater_dir = os.path.join(os.getcwd(),'wechat\\1\\')
        if not os.path.exists(curr_dir + "/Resources/video/"):
            os.mkdir(curr_dir + "/Resources/video/")
        savaPath = SourceSavePath + 'video/' + msg.file_name
        print(savaPath)
        Msg_content = savaPath
        msg.get_file(savaPath)
        # msg.reply_image(savaPath)

    print("***************************")
    # 打开数据库连接
    db = pymysql.connect("localhost", "root", "", "wechat")
    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    # SQL 插入语句
    sql = """INSERT INTO messages(msgTime,MsgType,GroupName,ActualNickName,Msg_content)VALUES ('%s','%s','%s','%s','%s')""" % (
    msgTime, MsgType, GroupName, ActualNickName, Msg_content)
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        # 如果发生错误则回滚
        db.rollback()
    # 关闭数据库连接
    db.close()



    if msg.sender.name == '3月29日1群'or msg.sender.name =='新疆业务中心云存储技术交流群'or msg.sender.name =='老板们':
        #print(msg.sender.name)
        #print(msg.text)
        #print(msg.text.isalnum())
        ret = re.match(r"^[0-9a-cA-C]\w{8}$", msg.text)
        if ret:
            ret = code.sysid(msg)
            print(ret)
            print("算序列号")
            return 'sys_id：{}\nold：{}\nnew：{}'.format(ret[0], ret[1],ret[2])
        else:
            print("匹配失败")

    # print(msg.sender.raw)
    if (msg.sender.name == '公孙墨岚' and msg.sender.raw[
        'Signature'] == 'robot') or msg.sender.name == "啦啦啦啦" or msg.sender.name == "3月29日2群" or msg.sender.name == "3月29日1群" or msg.sender.name == "云存储" or msg.sender.name == '老板们':
        print("老板来消息了！")
        if msg.text == "获取好友信息":
            print("获取好友信息")
            myFriends = bot.friends()
            get_friends(myFriends)
            msg.reply("更新好友信息完成！")
        elif msg.text == "好友头像拼图":
            file_return = get_friends_heardimg(bot, msg)
            if file_return == 1:
                msg.reply_image("wechat.png")
        elif msg.text == "文件发送":
            msg.reply_file("wechat.png")
        else:
            print("关键词处理方法")
            anw = similre(bot, msg)
            print(anw)
            if anw is not None:
                anw = anw.replace('\\', '\\\\')
                anw = anw.replace('\\\\n', '\n')
                anw = anw.replace('\\\\r', '\n')
                anw = anw.replace('\\\\', '')
                # anw = anw.replace('\\n','\\n')
                print(anw)
                # print(type(anw))
                return anw
# 进入 Python 命令行、让程序保持运行
#embed()

# 或者仅仅堵塞线程
bot.join()